package com.weshare.nd.netty.client;

import com.weshare.nd.cmd.ChatCommand;
import com.weshare.nd.model.ChatMessage;
import com.weshare.nd.netty.coder.ChatDecode;
import com.weshare.nd.netty.coder.ChatEncoder;
import com.weshare.nd.util.ScannerUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.apache.log4j.Logger;

public class ChatClient {
    private static final Logger logger = Logger.getLogger(ChatClient.class);
    public static String HOST = "127.0.0.1";
    public static int PORT = 9999;

    public static Bootstrap clientBoot;
    public static Channel clientChannel;

    public static String lastCommand;

    public static String clientName;

    public static void startClient() {
        EventLoopGroup group = new NioEventLoopGroup();

        clientBoot = new Bootstrap();

        clientBoot.group(group);
        clientBoot.channel(NioSocketChannel.class);
        clientBoot.option(ChannelOption.TCP_NODELAY, true);

        clientBoot.handler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("chatDecoder", new ChatDecode());
                pipeline.addLast("chatEncoder", new ChatEncoder());
                pipeline.addLast("clientHandler", new ChatClientHandler());
            }
        });

        try {
            clientChannel = clientBoot.connect(HOST, PORT).sync().channel();

            startTalk();

        } catch (Exception e) {
            logger.error(String.format("连接Server(IP[%s],PORT[%s])失败", HOST, PORT), e);
        }

    }


    public static void startTalk() {

        String readLine = null;

        while (true) {
            readLine = ScannerUtil.readInput();

            if ("logout".equals(readLine)) {
                clientChannel.close();

                logger.info("client logout.");
                break;
            } else {

                ChatMessage repMsg = new ChatMessage();

                if (ChatCommand.ASK.equals(lastCommand)) {

                    clientName = readLine;

                    repMsg.set(ChatCommand.ANSWER, clientName, "");

                    clientChannel.writeAndFlush(repMsg);
                } else {
                    repMsg.set(ChatCommand.TALK, clientName, readLine);

                    clientChannel.writeAndFlush(repMsg);

                }
            }
        }
    }

    public static void sendMsg(String msg) throws Exception {
        if (clientChannel != null) {
            clientChannel.writeAndFlush(msg).sync();
        } else {
            logger.warn("消息发送失败,连接尚未建立!");
        }
    }

    public static void main(String[] args) throws Exception {
        startClient();

        System.out.println("client start.");
    }
}